package com.common.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AdjustImageView extends ImageView {

    public AdjustImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public AdjustImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AdjustImageView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getDrawable().getIntrinsicWidth();
        int height = getDrawable().getIntrinsicHeight();
        int currentWidth = getMeasuredWidth();
        int currentHeight = getMeasuredHeight();
        if (width <= height) {
            float xx = (float) currentWidth / (float) width;
            currentHeight = (int) (xx * height);
            setMeasuredDimension(currentWidth, currentHeight);
        } else {
            float yy = (float) currentHeight / (float) height;
            currentWidth = (int) (yy * width);
            setMeasuredDimension(currentWidth, currentHeight);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        float scale = (float) getMeasuredWidth() / (float) drawable.getIntrinsicWidth();
        canvas.save();
        canvas.scale(scale, scale);
        drawable.draw(canvas);
        canvas.restore();
    }

}
